import { defineStore } from "pinia";
import { User, Todo, TodoForm } from "./types";
import { customRequest, request } from "./apis";

// 定义 userinfo store
export const useUserStore = defineStore("user", () => {
  const user = ref<User | null>(null);
  const login = (val: User) => {
      user.value = val;
    },
    logout = async () => {
      // 发起注销请求
      const { data } = await request("/logout");
      if (data.success) {
        // 将全局用户对象置空
        user.value = null;
      }
    },
    getUserInfo = async () => {
      if (user.value) return;
      const { data } = await customRequest<{ success: boolean; user: User }>(
        "/user/info"
      );
      if (data.success) {
        user.value = data.user;
      }
    };

  const avatar = computed(() =>
    user.value?.avatar
      ? `/avatars/${user.value.avatar}`
      : `/multi-avatar/${
          user.value?.nickname ? user.value.nickname : "default"
        }.svg`
  );
  return { user, login, logout, getUserInfo, avatar };
});

interface StatResponse {
  success: boolean;
  stat: {
    finished: { priority: string; count: number }[];
    notFinished: { priority: string; count: number }[];
  };
}
// define todos store
export const useTodosStore = defineStore("todos", () => {
//   type formValues = {
//     id: number;
//     title: string;
//     description: string;
//     priority: "normal" | "important" | "crucial";
// };
  //
  const todos = ref<Todo[]>([]);
  // 控制查询
  const conditions = reactive({
      days: "all",
      priority: "all",
      isFinished: "all",
    }),
    limit = 3,
    page = ref(1),
    isEnd = ref(false),
    count = ref(0);
  //   formValues = reactive<formValues>({
  //     id: 0,
  //     title: '',
  //     description: '',
  //     priority: 'normal'
  // })
  // 查询
  const search = async () => {
    // 如果已经加载到最后一页，则放弃发起请求。
    if (isEnd.value) return;
    // 发起查询请求
    const { data } = await request("/todos", {
      params: {
        ...conditions,
        offset: (page.value - 1) * limit,
        limit,
      },
    });
    
    if (data.success) {
      count.value = data.query!.count;
      page.value = data.query!.page;
      // 计算最大分页数
      const maxPage = Math.ceil(count.value / limit);
      // 判断是否加载完成
      isEnd.value = page.value >= maxPage;
      //
      if (page.value > 1) {
        todos.value.push(...data.query!.results);
      } else {
        todos.value = data.query!.results;
      }
    }
  };
  //
  const addTodo = async (todo: TodoForm) => {
      // 发起请求
      const { data } = await request<Todo>("/todos", {
        method: "post",
        data: todo,
      });
      // 只需处理成功的情况，失败会统一处理。
      if (data.success) {
        todos.value.unshift(data.object as Todo);
      }
      return data.success;
    },

    
    //修改
    editTodo = async (todo: TodoForm,id:number) => {
     const {data}=await request<Todo>( `/todos/${id}`,{
      method:"put",
      data:todo,
     });
     if (data.success) {
      todos.value=todos.value.map((i) =>
       i.id == data.object!.id ? (data.object as Todo) : i)
    }
    return data.success;
    },


    //删除
    deleteTodo = async(id:number) => {
      const {data}=await request<Todo>( `/todos/${id}`,{
        method:"DELETE",
       
       });
       if (data.success) {
        todos.value= todos.value.filter((todo) => todo.id !== id)
    }
    },
    finishTodo=async(id:number)=>{
      const {data}=await request<Todo>(`/todos/finish/${id}`,{
        method:"put",
      })
      if(data.success){
        todos.value = todos.value.map((todo) => todo.id == id ? data.object as Todo : todo)
      }
    }
  // 获取图标数据
  const chartData = ref<{ name: string; value: number }[]>([]);
  const finished = ref(0),
    notFinished = ref(0);
  const stat = async () => {
    const { data } = await customRequest<StatResponse>("/todos/stat");
    if (data.success) {
      // 转换数据格式
           chartData.value = [
        ...data.stat.finished.map((i) => ({
          name: "finished." + i.priority,
          value: i.count,
        })),
        ...data.stat.notFinished.map((i) => ({
          name: "notFinished." + i.priority,
          value: i.count,
        })),
      ];

      //
      finished.value = data.stat.finished.reduce((p, v) => p + v.count, 0);
      notFinished.value = data.stat.notFinished.reduce(
        (p, v) => p + v.count,
        0
      );
    }
  };
  // 对于对象或数组这样的复杂类型，可以使用深度侦听获取每个元素的变化。
  watch(todos, () => stat(), { deep: true });
  watch(
    conditions,
    () => {
      todos.value = [];
      page.value = 1;
      isEnd.value = false;
      count.value = 0;
      //
      search();
    },
    { deep: true }
  );
  return {
    todos,
    conditions,
    page,
    count,
    finished,
    notFinished,
    isEnd,
    chartData,
    search,
    addTodo,
    editTodo,
    deleteTodo,
    finishTodo
  };
});
